package Server.controller;

import Plug.operLog.OperLog;
import Plug.result.RetResponse;
import Plug.result.RetResult;
import Server.dao.*;
import Server.entity.*;
import Server.service.OrderService;
import Server.tool.BeanToJson;
import net.sf.json.JSONArray;
import net.sf.json.JSONNull;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.tomcat.jni.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.math.BigDecimal;
import java.util.*;

@RestController
@RequestMapping("OrderController")
public class OrderController {
    @Autowired
    private ShopCarDao shopCarDao;
    @Autowired
    private UsersSaleDao usersSaleDao;
    @Autowired
    private OrderService orderService;
    @Autowired
    private ShopOrderDao shopOrderDao;
    @Autowired
    private UserSiteDao userSiteDao;
    @Autowired
    private ShopOrderSaleDao shopOrderSaleDao;
    @Autowired
    private ShopOrderItemDao shopOrderItemDao;
    @Autowired
    private DictionarysDao dictionarysDao;
    @Autowired
    private UsersDao usersDao;
    @PersistenceContext
    EntityManager entityManager;

    @OperLog("购物车订单生成")
    @RequestMapping("CarOrder")
    public RetResult CarOrder(@RequestBody JSONObject jsonObject) {
        List<ShopCar> cars = new LinkedList<>();


        JSONArray car = jsonObject.getJSONArray("car");
        List list = JSONArray.toList(car);
        HashSet hs = new HashSet(list);
        JSONArray newjsonarray = JSONArray.fromObject(hs);
        for (Object obj : newjsonarray) {
            JSONObject jso = (JSONObject) obj;
            cars.add(shopCarDao.findByUuid(jso.getString("uuid")));
        }
        List<UsersSale> usersSale = new LinkedList<>();
        JSONArray jsonArray = jsonObject.getJSONArray("userSale");
        for (Object obj : jsonArray) {
            JSONObject jso = (JSONObject) obj;
            UsersSale stage = (UsersSale) BeanToJson.jsonTobean(jso.toString(), UsersSale.class);
            stage = usersSaleDao.findByUuid(stage.getUuid());
            usersSale.add(stage);
        }
        if (!jsonObject.getJSONObject("userSite").containsKey("uuid")) {
            return RetResponse.makeErrRsp("请选择一个收货地址");

        }
        UserSite userSite = userSiteDao.findByUuid(jsonObject.getJSONObject("userSite").getString("uuid"));
        return orderService.addOrder(cars, usersSale, userSite);
    }

    @RequestMapping("List")
    public RetResult List(@RequestBody JSONObject jsonObject) {
        /*ShopOrder entity = new ShopOrder();
        if (!StringUtils.isEmpty(jsonObject.getJSONObject("common").getString("name"))) {
            Users sp = new Users();
            sp.setName(jsonObject.getJSONObject("common").getString("name"));
            entity.setUsers(sp);
        }*/
        int page = Integer.parseInt(jsonObject.getString("page"));
        int size = Integer.parseInt(jsonObject.getString("limit"));
        page = (page - 1) * size;
        /*Users fspuser = (Users) SecurityUtils.getSubject().getSession().getAttribute("Users");
        fspuser = usersDao.findByUuid(fspuser.getUuid());
        ExampleMatcher matcher = ExampleMatcher.matching()
                .withMatcher("users.name", ExampleMatcher.GenericPropertyMatchers.contains());*/
        String sql = " select * from shop_order where 1=1 " + BeanToJson.bspcomm(jsonObject) + " order by modified_time desc,uuid limit " + page + "," + size;
        List<ShopOrder> ls = entityManager.createNativeQuery(sql, ShopOrder.class).getResultList();
       /* if (!fspuser.getRole().getUuid().equals("1")) {
            entity.setUsers(fspuser);
        }*/
        /*Example<ShopOrder> example = Example.of(entity, matcher);
        if (!StringUtils.isEmpty(jsonObject.getJSONObject("common").getString("createTime")) || !StringUtils.isEmpty(jsonObject.getJSONObject("common").getString("endTime"))) {
            Pageable pageable = PageRequest.of(page, size, Sort.Direction.DESC, "modified_Time");

            if (!StringUtils.isEmpty(jsonObject.getJSONObject("common").getString("name"))) {
                if (fspuser.getRole().getUuid().equals("2")) {
                    List<Users> usersList = usersDao.findByNameLike(jsonObject.getJSONObject("common").getString("name"));
                    Page<ShopOrder> userlist = shopOrderDao.findByTimeUS(fspuser.getUuid(), jsonObject.getJSONObject("common").getString("createTime"), jsonObject.getJSONObject("common").getString("endTime"), usersList.get(0).getUuid(), pageable);
                    return RetResponse.makeRsp(0, "成功", userlist.getContent(), (int) userlist.getTotalElements());
                } else {
                    List<Users> usersList = usersDao.findByNameLike(jsonObject.getJSONObject("common").getString("name"));
                    Page<ShopOrder> userlist = shopOrderDao.findByTime(jsonObject.getJSONObject("common").getString("createTime"), jsonObject.getJSONObject("common").getString("endTime"), usersList.get(0).getUuid(), pageable);
                    return RetResponse.makeRsp(0, "成功", userlist.getContent(), (int) userlist.getTotalElements());

                }
            } else {
                if (fspuser.getRole().getUuid().equals("2")) {
                    Page<ShopOrder> userlist = shopOrderDao.findByTime(fspuser.getUuid(), jsonObject.getJSONObject("common").getString("createTime"), jsonObject.getJSONObject("common").getString("endTime"), pageable);
                    return RetResponse.makeRsp(0, "成功", userlist.getContent(), (int) userlist.getTotalElements());
                } else {
                    Page<ShopOrder> userlist = shopOrderDao.findByTime(jsonObject.getJSONObject("common").getString("createTime"), jsonObject.getJSONObject("common").getString("endTime"), pageable);
                    return RetResponse.makeRsp(0, "成功", userlist.getContent(), (int) userlist.getTotalElements());
                }
            }
        } else {
            if (fspuser.getRole().getUuid().equals("2")) {
                if(entity.getUsers()!=null){
                    Pageable pageable = PageRequest.of(page, size, Sort.Direction.DESC, "modified_Time");
                    Page<ShopOrder> userlist = shopOrderDao.findUSALL(fspuser.getUuid(),entity.getUsers().getName(),pageable);
                    return RetResponse.makeRsp(0, "成功", userlist.getContent(), (int) userlist.getTotalElements());
                }else{
                    Pageable pageable = PageRequest.of(page, size, Sort.Direction.DESC, "modified_Time");
                    Page<ShopOrder> userlist = shopOrderDao.findUSALL(fspuser.getUuid(),pageable);
                    return RetResponse.makeRsp(0, "成功", userlist.getContent(), (int) userlist.getTotalElements());
                }

            } else {
                Pageable pageable = PageRequest.of(page, size, Sort.Direction.DESC, "modifiedTime");

            }
        }*/
        //Pageable pageable = PageRequest.of(page, size, Sort.Direction.DESC, "modified_Time");
        //Page<ShopOrder> userlist = shopOrderDao.findSql(sql, pageable);
        sql="select * from shop_order where 1=1 " + BeanToJson.bspcomm(jsonObject) + " order by modified_time desc,uuid";
        List<ShopOrder> lx = entityManager.createNativeQuery(sql, ShopOrder.class).getResultList();

        return RetResponse.makeRsp(0, "成功", ls, (int) lx.size());

    }

    @OperLog("管理员付款")
    @RequestMapping("pay")
    public RetResult pay(@RequestBody ShopOrder shopOrder) {
        shopOrder = shopOrderDao.findByUuid(shopOrder.getUuid());
        if (!shopOrder.getStatus().equals(ShopOrder.Status.NO)) {
            return RetResponse.makeErrRsp("当前状态不允许付款");
        } else {
            shopOrder.setStatus(ShopOrder.Status.YES);
            shopOrderDao.save(shopOrder);
            return RetResponse.makeOKRsp();
        }
    }

    @OperLog("管理员邮寄")
    @RequestMapping("mail")
    public RetResult mail(@RequestBody ShopOrder shopOrder) {
        ShopOrder entity = shopOrderDao.findByUuid(shopOrder.getUuid());
        if (!entity.getStatus().equals(ShopOrder.Status.YES)) {
            return RetResponse.makeErrRsp("当前状态不允许邮寄");
        } else {
            entity.setStatus(ShopOrder.Status.MAIL);
            entity.setNio(shopOrder.getNio());
            entity.setDiction(dictionarysDao.findByUuid(shopOrder.getDiction().getUuid()));
            shopOrderDao.save(entity);
            return RetResponse.makeOKRsp();
        }
    }

    @Autowired
    private MessageDao messageDao;

    @RequestMapping("GetOrderById")
    public RetResult GetOrderById(@RequestBody ShopOrder shopOrder) {
        shopOrder = shopOrderDao.findByUuid(shopOrder.getUuid());
        Users fspuser = (Users) SecurityUtils.getSubject().getSession().getAttribute("Users");
        fspuser = usersDao.findByUuid(fspuser.getUuid());
        if (!shopOrder.getUsers().equals(fspuser) && fspuser.getRole().equals("3")) {
            return RetResponse.makeErrRsp("这不是你的订单");
        }
        List<ShopOrderItem> shopOrderItems = shopOrderItemDao.findByShopOrder(shopOrder);
        List<ShopOrderSale> shopOrderSales = shopOrderSaleDao.findByShopOrder(shopOrder);
        Map<String, Object> mp = new HashMap<>();
        mp.put("order", shopOrder);
        mp.put("item", shopOrderItems);
        mp.put("sale", shopOrderSales);
        Message ms = messageDao.findByShopOrder(shopOrder);
        ms.setReadMI(1);
        messageDao.save(ms);
        return RetResponse.makeOKRsp(mp);
    }

    @OperLog("实收金额减免")
    @RequestMapping("anull")
    public RetResult anull(@RequestBody JSONObject jsonObject) {
        ShopOrder shopOrder = shopOrderDao.findByUuid(jsonObject.getString("uuid"));
        if (!shopOrder.getStatus().equals(ShopOrder.Status.NO)) {
            return RetResponse.makeErrRsp("只有未付款的订单可以减免");
        }
        BigDecimal anull = new BigDecimal(jsonObject.getDouble("anull"));
        if (anull.compareTo(BigDecimal.ZERO) > 0) {
            shopOrder.setAnnul(shopOrder.getAnnul().add(anull.abs()));
            shopOrder.setMoney(shopOrder.getMoney().subtract(anull.abs()));
        } else {
            shopOrder.setAnnul(shopOrder.getAnnul().subtract(anull.abs()));
            shopOrder.setMoney(shopOrder.getMoney().add(anull.abs()));
        }
        shopOrderDao.save(shopOrder);
        return RetResponse.makeOKRsp();
    }
    @RequestMapping("GetOrderItem")
    public RetResult ClassList(@RequestBody JSONObject jsonObject){
        ShopOrderItem entity = (ShopOrderItem) BeanToJson.jsonTobean(jsonObject.getJSONObject("common").toString(), ShopOrderItem.class);
        int page = Integer.parseInt(jsonObject.getString("page"))-1;
        int size = Integer.parseInt(jsonObject.getString("limit"));
        Pageable pageable = PageRequest.of(page, size, Sort.Direction.DESC, "uuid");
        ExampleMatcher matcher = ExampleMatcher.matching()
                .withMatcher("name", ExampleMatcher.GenericPropertyMatchers.contains());
        Example<ShopOrderItem> example = Example.of(entity,matcher);
        Page<ShopOrderItem> userlist = shopOrderItemDao.findAll(example,pageable);
        return RetResponse.makeRsp(0, "成功", userlist.getContent(), (int) userlist.getTotalElements());
    }
}
